from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time
import schedule
import datetime
import sys

def login(driver):
    """登录处理"""
    try:
        driver.get('https://smartwhp.lenovo.com/wui/index.html?#/main/portal/portal-2-1?menuIds=0,2&menuPathIds=0,2&_key=pfyz9c')
        print(f"{get_current_time()} 页面加载中...")

        # 等待登录表单加载
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.ID, "loginid"))
        )
        
        # 输入用户名和密码
        username_input = driver.find_element(By.ID, 'loginid')
        username_input.clear()
        username_input.send_keys('91009751')
        
        password_input = driver.find_element(By.ID, 'userpassword')
        password_input.clear()
        password_input.send_keys('9292lijun')
        
        # 点击登录按钮
        login_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//button[@id="submit" and .//span="登 录"]'))
        )
        login_button.click() 
        print(f"{get_current_time()} 登录按钮已点击")
        
        # 处理登录后的确认弹窗
        try:
            confirm_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, 
                    '//div[contains(@class, "ant-confirm-btns")]//button[contains(@class, "ant-btn-primary") and .//span="确 认"]'))
            )
            confirm_button.click()
            print(f"{get_current_time()} 登录确认按钮点击成功")
        except TimeoutException:
            print(f"{get_current_time()} 未出现登录确认弹窗，继续执行")
        
        # 等待登录完成
        time.sleep(3)
        print(f"{get_current_time()} 登录成功")
        return True
        
    except Exception as e:
        print(f"{get_current_time()} 登录出错: {str(e)}")
        return False


def process_pending_approvals(driver):
    try:
        # 等待待审批列表加载
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.XPATH, '//a[contains(@data-link, "/workflow/request/ViewRequestForwardSPA.jsp")]'))
        )
        
        print(f"{get_current_time()} 开始处理待审批申请...")
        index = 1
        
        while True:
            # 每次重新获取待审批链接
            approval_links = driver.find_elements(
                By.XPATH, 
                '//a[contains(@data-link, "/workflow/request/ViewRequestForwardSPA.jsp") and @data-requestid]'
            )
            
            if not approval_links:
                print(f"{get_current_time()} 没有更多待审批申请")
                break
                
            print(f"\n{get_current_time()} 发现 {len(approval_links)} 个待审批申请，处理第 {index} 个...")
            
            try:
                link = approval_links[0]
                request_id = link.get_attribute("data-requestid")
                request_title = link.get_attribute("title") or "未知标题"
                print(f"{get_current_time()} 处理申请 - ID: {request_id}, 标题: {request_title}")
                original_window = driver.current_window_handle
                
                # 点击打开申请详情
                WebDriverWait(driver, 10).until(EC.element_to_be_clickable(link)).click()
                print(f"{get_current_time()} 已打开申请详情")

                # 等待新窗口打开
                WebDriverWait(driver, 15).until(lambda d: len(d.window_handles) > 1)

                # 切换到新窗口
                new_window = [h for h in driver.window_handles if h != original_window][0]
                driver.switch_to.window(new_window)

                # 点击批准按钮
                approve_button = WebDriverWait(driver, 20).until(
                    EC.element_to_be_clickable((By.XPATH, '//div[contains(text(), "批 准")]/parent::button'))
                )
                approve_button.click()
                print(f"{get_current_time()} 已点击批准按钮")
                
                # 点击确认按钮
                confirm_button = WebDriverWait(driver, 15).until(
                    EC.element_to_be_clickable((By.XPATH, '//button[contains(@class, "ant-btn-primary") and .//span="确 定"]'))
                )
                confirm_button.click()
                print(f"{get_current_time()} 已点击确认按钮，完成审批")
                
                # 等待新窗口关闭
                WebDriverWait(driver, 15).until(lambda d: new_window not in d.window_handles)
                
                # 返回原窗口并刷新
                driver.switch_to.window(original_window)
                driver.refresh()
                WebDriverWait(driver, 15).until(
                    EC.presence_of_element_located((By.XPATH, '//a[contains(@data-link, "/workflow/request/ViewRequestForwardSPA.jsp")]'))
                )
                
                index += 1
                time.sleep(1)
                
            except Exception as e:
                print(f"{get_current_time()} 处理第 {index} 个申请时出错: {str(e)}")
                # 出错处理
                try:
                    if len(driver.window_handles) > 1:
                        for handle in driver.window_handles:
                            if handle != original_window:
                                driver.switch_to.window(handle)
                                driver.close()
                        driver.switch_to.window(original_window)
                    driver.refresh()
                except:
                    pass
                index += 1
                continue
        
        print(f"\n{get_current_time()} 所有待审批申请处理完毕")
        return True
        
    except TimeoutException:
        print(f"{get_current_time()} 未找到待审批申请列表，可能没有待审批内容")
        return False
    except Exception as e:
        print(f"{get_current_time()} 处理申请时发生错误: {str(e)}")
        return False


def get_current_time():
    """获取当前时间字符串"""
    return datetime.datetime.now().strftime("%H:%M:%S")


def run_approval_task():
    """执行审批任务的主函数"""
    print(f"\n{get_current_time()} 开始新一轮审批任务...")
    
    # 初始化浏览器
    driver = webdriver.Chrome()
    driver.maximize_window()
    
    try:
        # 登录并处理审批
        if login(driver):
            process_pending_approvals(driver)
    finally:
        # 无论成功失败都关闭浏览器
        print(f"{get_current_time()} 关闭浏览器")
        driver.quit()


if __name__ == "__main__":
    print(f"{get_current_time()} 程序启动，将在每个整点和半点执行审批任务")
    
    # 安排任务：每个整点和半点执行
    schedule.every().hour.at(":00").do(run_approval_task)
    schedule.every().hour.at(":30").do(run_approval_task)
    
    # 立即执行一次
    run_approval_task()
    
    # 保持程序运行
    try:
        while True:
            schedule.run_pending()
            time.sleep(1)
    except KeyboardInterrupt:
        print(f"\n{get_current_time()} 程序被手动终止")
        sys.exit(0)

    